//
//  HistoryLiveViewController.m
//  CYWFrame
//
//  Created by Macx on 2017/12/2.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "HistoryLiveViewController.h"

#import "HistoryLiveTableViewCell.h"
#import "Live.h"


#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>
#import <Masonry.h>

@interface HistoryLiveViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NSMutableArray *liveArr;
@property (nonatomic, assign) NSInteger page; // 网络请求页数

@property (nonatomic, strong) MPMoviePlayerController *moviePlayer;

@end

@implementation HistoryLiveViewController{
    UITableView *_tableView;
}

- (void)viewWillAppear:(BOOL)animated {
    
    // 当当前页面顶部位置
    if (self.page == 1) {
        [self GETHistoryLive];
    }
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.page = 1;
    
    [self buildUI];
    
    [self GETHistoryLive];
    
    [self refreshData];
    
//    [self.moviePlayer play];
    
//    [self addNofi];
}


#pragma mark ==========构建UI==========
- (void)buildUI {
    
    self.view.backgroundColor = UISeparatedColorRGB;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 1, SCREEN_WIDTH, SCREEN_HEIGHT-(44+[LZCTools textSizeWithText:@"x" font:kUHSystemFontWithSize(14)].height*3+15+4*SW(15))) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [[UIView alloc]init];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.rowHeight = UITableViewAutomaticDimension;
    _tableView.estimatedRowHeight = 440.0f;
    [_tableView registerClass:[HistoryLiveTableViewCell class] forCellReuseIdentifier:@"cell"];
    
}

#pragma mark ==========更新数据==========
- (void)refreshData {
    __weak typeof (self) weakSelf = self;
    
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        NSLog(@"下拉刷新");
        weakSelf.page = 1;
        [weakSelf GETHistoryLive];
    }];
    
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        NSLog(@"上拉加载");
        weakSelf.page++;
        [weakSelf GETHistoryLive];
    }];
    
}

#pragma mark ==========UITableView==========
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"点击tableView.cell = %ld", indexPath.row);
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.liveArr.count;
//    return 10;
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    return 300;
//}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.1)];
    view.backgroundColor = UISeparatedColorRGB;
    return view;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.1)];
    view.backgroundColor = UISeparatedColorRGB;
    return view;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HistoryLiveTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    Live *model = self.liveArr[indexPath.row];

    cell.model = model;
    
//    [cell.cover addTarget:self action:@selector(play)];
    cell.cover.tag = indexPath.row;
    [cell.cover addActionWithblock:^{
       
        NSURL * movieurl = [NSURL URLWithString:model.mp4_record_uri[0]];
        
        MPMoviePlayerViewController *player = [[MPMoviePlayerViewController alloc] initWithContentURL:movieurl];
        
        
        // 水印
        UIButton *watermark = [UIButton buttonWithType:UIButtonTypeCustom];
        [player.view addSubview:watermark];
        [watermark setImage:IMAGE(@"watermark") forState:UIControlStateNormal];
        watermark.userInteractionEnabled = NO;
        [watermark mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_offset(SW(10));
            make.right.mas_offset(0);
            make.width.offset(SW(4));
            make.height.offset(SW(8));
        }];
        
        [self presentMoviePlayerViewControllerAnimated:player];
        
    }];
    
    cell.deleteBtn.tag = indexPath.row;
    [cell.deleteBtn addTarget:self action:@selector(deleteLive:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}
- (void)deleteLive:(UIButton *)btn {
    
    Live *model = self.liveArr[btn.tag];
    
    NSString *url = [NSString stringWithFormat:@"%@/%ld", APILives, model.liveId];
    
    [[NetworkTool sharedTool] requestWithName:@"删除历史直播" URLString:url parameters:nil method:@"DELETE" callBack:^(id responseObject) {
        [self.liveArr removeObjectAtIndex:btn.tag];
        [_tableView reloadData];
    }];
    
}

#pragma mark ==========响应方法==========
// 获取动态
- (void)GETHistoryLive {
    
    if (GetUserDefaule(Token) == NULL) {
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [hud hideAnimated:YES afterDelay:1.0];
        double delayInSeconds = 1.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            //执行事件
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [self GETHistoryLive];
        });
        return;
        
    }
    //GET /lives 获取直播列表 ? page 页码 tag_id 分类ID per_page 每页显示数 keyword 关键词 支持直播标题
    
    NSDictionary *param = @{@"page":[NSString stringWithFormat:@"%ld", self.page],
                  @"per_page":@"10",
                  @"state":@"recorded",
                  @"user_id":_user_id};
    
    [[NetworkTool sharedTool] requestWithName:@"获取历史直播" URLString:APILives parameters:param method:@"GET" callBack:^(id responseObject) {
        
        NSArray *arr = responseObject[@"data"];
        
        if (self.page == 1) {
            [self.liveArr removeAllObjects];
        }
        
        if (arr.count == 0) {
            self.page--;
            if (self.page == 0) {
                self.page = 1;
            }
        }
        
        
        for (NSDictionary *dic in arr) {
            Live *model = [[Live alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.liveArr addObject:model];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
            [_tableView reloadData];
        });
        
    }];

}

// 懒加载
- (NSMutableArray *)liveArr {
    if (_liveArr == nil) {
        _liveArr = [[NSMutableArray alloc] init];
    }
    return _liveArr;
}

#pragma mark =====shipin======

/**
 *  添加视频播放的通知
 */

/*
- (void)addNofi

{
    
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(playbackstateDidChange:)
     
                                                 name:MPMoviePlayerPlaybackStateDidChangeNotification   //播放状态改变，可配合playbakcState属性获取具体状态
     
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(playDidFinish:) //媒体播放完成或用户手动退出，具体完成原因可以通过通知userInfo中的key为MPMoviePlayerPlaybackDidFinishReasonUserInfoKey的对象获取
     
                                                 name:MPMoviePlayerPlaybackDidFinishNotification
     
                                               object:nil];
    
}





- (void)playbackstateDidChange:(NSNotification *)noti

{
    
    switch
    (self.moviePlayer.playbackState) {
            
        case
        MPMoviePlaybackStateInterrupted:
            
            //中断
            
            NSLog(@"中断");
            
            break;
            
        case
        MPMoviePlaybackStatePaused:
            
            //暂停
            
            NSLog(@"暂停");
            
            break;
            
        case
        MPMoviePlaybackStatePlaying:
            
            //播放中
            
            NSLog(@"播放中");
            
            break;
            
        case
        MPMoviePlaybackStateSeekingBackward:
            
            //后退
            
            NSLog(@"后退");
            
            break;
            
        case
        MPMoviePlaybackStateSeekingForward:
            
            //快进
            
            NSLog(@"快进");
            
            break;
            
        case
        MPMoviePlaybackStateStopped:
            
            //停止
            
            NSLog(@"停止");
            
            break;
            
            
            
        default:
            
            break;
            
    }
    
}



- (void)playDidFinish:(NSNotification *)noti {
    //播放完成
    NSLog(@"播放完成");
    
}
*/
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
